package career_handler

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"mime/multipart"
	"net/http"
	"peilian-api/app/global/bind"
	"peilian-api/app/global/databases/tables"
	"peilian-api/app/global/log"
	"peilian-api/app/global/variable"
	"peilian-api/app/services/career_service"
	"peilian-api/app/services/label_service"
	"peilian-api/app/services/tiku_service"
	"peilian-api/utils/format"
	"time"
)

func DiscussionList(ctx *gin.Context) {
	var req career_service.GetDiscussionReq
	if err := bind.ShouldBinding(ctx, &req); err != nil {
		format.NewResponseJson(ctx).Err(500, err.Error(), []string{})
		return
	}
	careers, err := career_service.GetDiscussionList(ctx, req)
	if err != nil {
		format.NewResponseJson(ctx).Err(500, err.Error(), []string{})
		return
	}
	format.NewResponseJson(ctx).SuccessObj(careers)
}

type ruleInfo struct {
	Text        string `json:"text"`
	VideoStatus int    `json:"video_status"`
	Video       string `json:"video"`
	PcVideo     string `json:"pc_video"`
}

type DiscussionResp struct {
	Discussion tables.Career    `json:"discussion"`
	Rule       ruleInfo         `json:"rule"`
	Question   *tables.Question `json:"question"`
}

func DiscussionInfo(c *gin.Context) {
	agentId, _ := c.Get("aid")
	careerId := c.Param("careerId")
	resp := DiscussionResp{}
	var career tables.Career
	if err := variable.DB.MySQL.Where(
		"career_type = 'discussion' and is_available <> ? and agent_id = ?", 2, agentId,
	).First(&career, careerId).Error; err != nil {
		format.NewResponseJson(c).Err(http.StatusBadRequest, err.Error())
		return
	}
	resp.Discussion = career
	// 获取问题信息
	var question tables.Question
	err := variable.DB.MySQL.Model(&tables.Question{}).Where("type='rule' and career_id=? and source=4", career.ID).First(&question).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		format.NewResponseJson(c).Err(http.StatusInternalServerError, err.Error())
		return
	}
	var rule ruleInfo
	if question.ID != 0 {
		rule.Video = question.Video
		rule.VideoStatus = question.VideoStatus
		rule.Text = question.Text
		rule.PcVideo = question.PcVideo
	}
	resp.Rule = rule
	// 获取绑定的问题
	var questions []tables.CustomCareer

	subQuery := variable.DB.MySQL.Model(&tables.CustomCareer{}).Preload("Question").
		Where("career_id=?", careerId).Find(&questions).Order("tag")
	if err := subQuery.Error; err != nil && err != gorm.ErrRecordNotFound {
		format.NewResponseJson(c).Err(http.StatusInternalServerError, err.Error())
		return
	}
	if len(questions) != 0 {
		resp.Question = questions[0].Question
	}

	format.NewResponseJson(c).SuccessObj(&resp)
	return
}

type DiscussionReq struct {
	Name              string                `form:"name"`
	CareerPhotoStream *multipart.FileHeader `form:"career_photo"`
	CareerMsg         *string               `form:"career_msg"`
	Label             string                `form:"label"`
	IsRelease         *bool                 `form:"is_release"`
	QuestionNum       int                   `form:"question_num"`

	Rule *string `form:"rule"` // 另外配置的规则信息
}

func DiscussionCreate(c *gin.Context) {
	fmt.Printf("DiscussionCreate:%+v\n", c.Request)
	var req DiscussionReq
	if err := c.ShouldBind(&req); err != nil {
		format.NewResponseJson(c).Err(http.StatusBadRequest, err.Error())
		return
	}
	fmt.Printf("DiscussionCreate req:%+v\n", req)
	var career = tables.Career{
		Name:        req.Name,
		CareerMsg:   req.CareerMsg,
		Label:       req.Label,
		IsRelease:   req.IsRelease,
		QuestionNum: req.QuestionNum,
	}
	photo, err := CareerPhotoHandler(req.CareerPhotoStream)
	if err != nil {
		if len(photo) == 0 {
			format.NewResponseJson(c).Err(http.StatusBadRequest, err.Error())
			return
		} else {
			isDefault := true
			career.PhotoIsDefault = &isDefault
		}
	}
	career.CareerPhoto = variable.Config.UfsInfo.UfsUrl + photo
	career.SetCustomDefault()
	agentId, exist := c.Get("aid")
	if !exist {
		format.NewResponseJson(c).Err(http.StatusBadRequest, "agent_id未解析到")
		return
	}
	career.AgentId = agentId.(uint)

	if err := career.SaveDiscussionValidate(); err != nil {
		format.NewResponseJson(c).Err(http.StatusBadRequest, err.Error())
		return
	}
	var n int64
	variable.DB.MySQL.Model(&tables.Career{}).Where("name=? and agent_id=?", career.Name, agentId).Count(&n)
	if n > 0 {
		format.NewResponseJson(c).Err(http.StatusBadRequest, "岗位名称已经存在")
		return
	}
	db := tables.CustomLabel{}
	label := db.GetLabelByName(career.Name)
	if label != nil && label.ID != 0 {
		career.ReportType = "web"
	}
	career.CareerType = "discussion"
	if err := variable.DB.MySQL.Create(&career).Error; err != nil {
		format.NewResponseJson(c).Err(http.StatusInternalServerError, err.Error())
		return
	}
	// 生成对应的标签
	if label == nil || label.ID == 0 {
		// 生成对应的标签
		_, err = label_service.CreateLabel(c, label_service.CreateLabelReq{JobName: career.Name})
		if err != nil {
			log.Logger.ErrorF(c, fmt.Sprintf("CreateLabel error :%+v", err))
		}
	}
	// 创建对应的说明信息
	if req.Rule != nil && *req.Rule != "" {
		var question = tables.Question{
			CareerID: career.ID,
			Text:     *req.Rule,
			Type:     "rule",
			Source:   4,
		}
		if err := variable.DB.MySQL.Create(&question).Error; err != nil {
			format.NewResponseJson(c).Err(http.StatusInternalServerError, err.Error())
			return
		}
		//新创建一个问题，需要生成视频
		go func() {
			err := new(tiku_service.TikuService).GenerateVideo(c, question.ID, "")
			if err != nil {
				format.NewResponseJson(c).ErrObj(err.Code, err.Err.Error())
				return
			}
		}()
	}

	format.NewResponseJson(c).SuccessObj(career)
}

type DiscussionDIHumanReq struct {
	Content string `json:"content" form:"content" validate:"required"`
}

func DiscussionDIHumanCreate(c *gin.Context) {
	fmt.Printf("DiscussionCreate:%+v\n", c.Request)
	var req DiscussionDIHumanReq
	if err := bind.ShouldBinding(c, &req); err != nil {
		format.NewResponseJson(c).Err(30001, err.Error())
		return
	}
	fmt.Printf("DiscussionCreate req:%+v\n", req)

	var question = tables.Question{
		CareerID: 0,
		Text:     req.Content,
		Type:     "discussion-rule",
		Source:   4,
	}
	if err := variable.DB.MySQL.Create(&question).Error; err != nil {
		format.NewResponseJson(c).Err(http.StatusInternalServerError, err.Error())
		return
	}
	//新创建一个问题，需要生成视频
	go func() {
		err := new(tiku_service.TikuService).GenerateVideo(c, question.ID, "")
		if err != nil {
			format.NewResponseJson(c).ErrObj(err.Code, err.Err.Error())
			return
		}
	}()
	type respStruct struct {
		Id     uint   `json:"id"`
		Status int    `json:"status"`
		Text   string `json:"text"`
	}
	resp := respStruct{
		Id:     question.ID,
		Status: question.VideoStatus,
		Text:   question.Text,
	}

	format.NewResponseJson(c).SuccessObj(resp)
}

type DiscussionGetDIHumanReq struct {
	Id uint `form:"id" json:"id" validate:"required"`
}

func DiscussionGetDIHuman(c *gin.Context) {
	var req DiscussionGetDIHumanReq
	if err := c.ShouldBind(&req); err != nil {
		format.NewResponseJson(c).Err(http.StatusBadRequest, err.Error())
		return
	}

	var question tables.Question
	err := variable.DB.MySQL.Model(&tables.Question{}).Where("id=? and source=4", req.Id).First(&question).Error
	if err != nil {
		format.NewResponseJson(c).Err(http.StatusInternalServerError, err.Error())
		return
	}
	var rule ruleInfo
	if question.ID != 0 {
		rule.Video = question.Video
		rule.VideoStatus = question.VideoStatus
		rule.Text = question.Text
		rule.PcVideo = question.PcVideo
	}
	format.NewResponseJson(c).SuccessObj(rule)
}

func DiscussionUpdate(c *gin.Context) {
	var careerReq DiscussionReq
	if err := c.ShouldBind(&careerReq); err != nil {
		format.NewResponseJson(c).Err(http.StatusBadRequest, err.Error())
		return
	}
	agentId, exist := c.Get("aid")
	if !exist {
		format.NewResponseJson(c).Err(http.StatusBadRequest, "agent_id未解析到")
		return
	}
	// 获取旧的信息
	careerId := c.Param("careerId")
	var hasCareer tables.Career
	err := variable.DB.MySQL.Model(&tables.Career{}).Where("id=? and agent_id=?", careerId, agentId).First(&hasCareer).Error
	if err != nil || hasCareer.ID == 0 {
		format.NewResponseJson(c).Err(http.StatusBadRequest, fmt.Sprintf("find Discussion error:%+v", err))
		return
	}
	if careerReq.Name != "" {
		hasCareer.Name = careerReq.Name
	}
	if careerReq.CareerMsg != nil {
		hasCareer.CareerMsg = careerReq.CareerMsg
	}
	if careerReq.Label != "" {
		hasCareer.Label = careerReq.Label
	}

	photo, err := CareerPhotoHandler(careerReq.CareerPhotoStream)
	fmt.Printf("CareerPhotoHandler error -->%+v\n", err)
	if err == nil {
		hasCareer.CareerPhoto = variable.Config.UfsInfo.UfsUrl + photo
	}
	if err := hasCareer.UpdateDiscussionValidate(); err != nil {
		format.NewResponseJson(c).Err(http.StatusBadRequest, err.Error())
		return
	}

	if careerReq.IsRelease != nil && *careerReq.IsRelease {
		if *hasCareer.IsRelease {
			format.NewResponseJson(c).Err(http.StatusBadRequest, "该岗位已经发布")
			return
		}
		if hasCareer.QuestionNum <= 0 {
			format.NewResponseJson(c).Err(http.StatusBadRequest, "请绑定面试题目")
			return
		}
	}
	if careerReq.Name != "" {
		db := tables.CustomLabel{}
		label := db.GetLabelByName(careerReq.Name)
		if label != nil && label.ID != 0 {
			hasCareer.ReportType = "web"
		} else {
			// 生成对应的标签
			_, err = label_service.CreateLabel(c, label_service.CreateLabelReq{JobName: careerReq.Name})
			if err != nil {
				log.Logger.ErrorF(c, fmt.Sprintf("CreateLabel error :%+v", err))
			}
			hasCareer.ReportType = "custom"
		}
	}
	if careerReq.Rule != nil && *careerReq.Rule != "" {
		var createVideo bool
		var question tables.Question
		err := variable.DB.MySQL.Model(&tables.Question{}).Where("type='rule' and career_id=? and source=4", hasCareer.ID).First(&question).Error
		if err == gorm.ErrRecordNotFound {
			question = tables.Question{
				CareerID: hasCareer.ID,
				Text:     *careerReq.Rule,
				Type:     "rule",
				Source:   4,
			}
			if err := variable.DB.MySQL.Create(&question).Error; err != nil {
				format.NewResponseJson(c).Err(http.StatusInternalServerError, err.Error())
				return
			}
			createVideo = true
		} else if err != nil {
			format.NewResponseJson(c).Err(http.StatusInternalServerError, err.Error())
			return
		}
		if question.Text != *careerReq.Rule {
			question.Text = *careerReq.Rule
			createVideo = true
			if err := variable.DB.MySQL.Model(&tables.Question{}).Where("id=?", question.ID).Updates(&question).Error; err != nil {
				format.NewResponseJson(c).Err(http.StatusBadRequest, err.Error())
				return
			}
		}
		if createVideo {
			//新创建一个问题，需要生成视频
			go func() {
				err := new(tiku_service.TikuService).GenerateVideo(c, question.ID, "")
				if err != nil {
					format.NewResponseJson(c).ErrObj(err.Code, err.Err.Error())
					return
				}
			}()
		}

	}

	if err := variable.DB.MySQL.Model(&tables.Career{}).Where("id=?", careerId).Updates(&hasCareer).Error; err != nil {
		format.NewResponseJson(c).Err(http.StatusBadRequest, err.Error())
		return
	}
	format.NewResponseJson(c).SuccessObj(&hasCareer)
}

func DiscussionDelete(c *gin.Context) {
	careerId := c.Param("careerId")
	if err := variable.DB.MySQL.Transaction(func(tx *gorm.DB) error {
		if err := variable.DB.MySQL.Model(&tables.Career{}).Where("id=?", careerId).
			Update("name", gorm.Expr("concat(name,?)", time.Now().Format("20060102030405"))).Error; err != nil {
			return err
		}
		if err := variable.DB.MySQL.Delete(&tables.Career{}, careerId).Error; err != nil {
			return err
		}
		if err := variable.DB.MySQL.Delete(&tables.CustomCareer{}, "career_id=?", careerId).Error; err != nil {
			return err
		}
		return nil
	}); err != nil {
		format.NewResponseJson(c).Err(http.StatusBadRequest, err.Error())
		return
	}

	format.NewResponseJson(c).SuccessObj(struct{}{})
}
